<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="code">
        <el-input style="width: 260px"
          v-model="queryParams.code"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input style="width: 260px"
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-select v-model="queryParams.deptId" @keyup.enter.native="handleQuery" style="width: 260px;" clearable>
          <el-option v-for="dept in deptCderp" :key="dept.deptId" :value="dept.deptId" :label="dept.deptName">{{dept.deptName}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width:260px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="available" >
        <el-select v-model="queryParams.available" @keyup.enter.native="handleQuery" style="width: 260px">
          <el-option value="" label="全部">全部</el-option>
          <el-option value="1" label="启用">启用</el-option>
          <el-option value="0" label="停用">停用</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:Shop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:Shop:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:Shop:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:Shop:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ShopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="ID" align="center" prop="id" />-->
      <el-table-column label="编号" align="center" prop="code" width="160"/>
      <el-table-column label="名称" align="center" prop="name" width="110"/>
      <el-table-column label="仓库名称" align="center" prop="cname" width="110"/>
      <el-table-column label="所属部门" align="center" prop="dname" width="110"/>
      <el-table-column label="状态" align="center" prop="available" width="130">
        <template slot-scope="scope">
          <span>{{ scope.row.available == 1 ? "启用" : "停用"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" width="150" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="description" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="getShow(scope.row)"
            v-hasPermi="['system:Shop:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:Shop:edit']"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:Shop:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" style="width: 230px;" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="scId" >
          <el-select v-model="form.scId" @keyup.enter.native="handleQuery" style="width: 230px;" clearable>
            <el-option v-for="center in StoreCenterInfoList" :key="center.id" :value="center.id" :label="center.name">{{center.name}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-select v-model="form.deptId" @keyup.enter.native="handleQuery" style="width: 230px;" clearable>
            <el-option v-for="dept1 in deptCderp" :key="dept1.deptId" :value="dept1.deptId" :label="dept1.deptName">{{dept1.deptName}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择位置">
          <div  id="gaodeMapContainer" style="width: 870px; height: 300px;" ></div>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" placeholder="请输入备注" style="width: 870px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看" :visible.sync="open1" width="900px" append-to-body>
      <el-descriptions :column="2" border :data="haseShow">
        <el-descriptions-item label="编号">{{haseShow.code}}</el-descriptions-item>
        <el-descriptions-item label="名称">{{haseShow.name}}</el-descriptions-item>
        <el-descriptions-item label="仓库名称">{{haseShow.cname}}</el-descriptions-item>
        <el-descriptions-item label="所属部门">{{haseShow.dname}}</el-descriptions-item>
        <el-descriptions-item label="经度">{{haseShow.lng}}</el-descriptions-item>
        <el-descriptions-item label="纬度">{{haseShow.lat}}</el-descriptions-item>
        <el-descriptions-item label="状态">{{haseShow.available  == 1 ? "启用" : "停用"}}</el-descriptions-item>
        <el-descriptions-item label="备注">{{haseShow.description}}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listShop, getShop, delShop, addShop, updateShop } from "@/api/system/Shop";
import { listDeptCderp } from "@/api/system/deptCderp";
import { listStoreCenterInfo } from '@/api/system/StoreCenterInfo'

export default {
  name: "Shop",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,

      total: 0,
      //编号
      codeNum:null,
      // 门店表格数据
      ShopList: [],
      deptCderp:[],
      haseShow:[],
      //仓库
      StoreCenterInfoList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,

      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        deptId: null,
        available: null,
        createTime: null,
      },
      queryParams1: {
        pageNum: 1,
        pageSize: 100000
      },
      query: {
        categoryType: 1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        scId:[
          { required: true, message: "仓库名称不能为空", trigger: "blur" }
        ],
        deptId:[
          { required: true, message: "所属部门不能为空", trigger: "blur" }
        ],
        available: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      },
      selectedPosition: {     // 存储选中的经纬度
        lng: null,
        lat: null
      },
      mapInstance: null,      // 高德地图实例
      marker: null            // 地图标记
    };
  },
  beforeCreate() {
    // 动态加载高德地图SDK
    const script = document.createElement("script");
    script.src = "https://webapi.amap.com/maps?v=2.0&key=2796a17458f00d2eb70d1ac4470532f7";
    script.async = true;
    script.onload = () => {
      this.$emit("amap-loaded"); // 自定义事件通知组件SDK已加载
    };
    document.head.appendChild(script);
  },
  created() {
    this.getList();
    this.getDeptList();
    this.getStoreCenterInfoList();
    this.$on("amap-loaded", () => {
      this.initGaodeMap(); // 在SDK加载完成后初始化地图
    });
  },
  methods: {
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listShop(this.queryParams).then(response => {
        this.ShopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //部门
    getDeptList() {
      this.loading = true;
      listDeptCderp(null).then(response => {
        this.deptCderp = response.rows;
        console.log(this.deptCderp)
        this.loading = false;
      });
    },
    //仓库
    getStoreCenterInfoList(){
      this.loading = true;
      listStoreCenterInfo(this.query).then(response => {
        this.StoreCenterInfoList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();

      // 清理地图相关状态
      if (this.marker) {
        this.mapInstance.remove(this.marker);
        this.marker = null;
      }

      this.selectedPosition = { lng: null, lat: null };
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        deptId: null,
        lng: null,
        lat: null,
        description: null,
        available: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加门店";

      const that = this;
      this.$nextTick(() => {
        if (!this.mapInstance) {
          this.initGaodeMap();
        }
        // 清除旧标记
        if (that.marker) {
          that.mapInstance.remove(that.marker);
        }
      });
    },
    initGaodeMap() {

      const that = this;
      const container = document.getElementById("gaodeMapContainer");
      if (!container) {
        console.error("地图容器未找到，请确保 DOM 已渲染");
        return;
      }
      // 如果已有地图实例，先移除旧的标记和地图
      if (this.mapInstance) {
        if (this.marker) {
          this.mapInstance.remove(this.marker);
          this.marker = null;
        }
        this.mapInstance.destroy(); // 销毁旧地图实例
      }

      // 创建新地图实例
      this.mapInstance = new AMap.Map(container);
      // 点击地图获取坐标
      this.mapInstance.on("click", function(e) {
        that.selectedPosition.lng = e.lnglat.getLng();
        that.selectedPosition.lat = e.lnglat.getLat();

        // 清除旧标记
        if (that.marker) {
          that.mapInstance.remove(that.marker);
        }

        // 添加新标记
        that.marker = new AMap.Marker({
          position: new AMap.LngLat(that.selectedPosition.lng, that.selectedPosition.lat)
        });
        that.mapInstance.add(that.marker);
      });
    },
    //查看按钮操作
    getShow(row) {
      this.loading = true;
      const id = row.id || this.ids
      getShop(id).then(response => {
        this.haseShow = response.data;
        this.open1=true;
        this.loading = false;
        this.title = "查看";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getShop(id).then(response => {
        this.form = response.data;
        // 清除旧标记
        if (this.marker) {
          this.mapInstance.remove(this.marker);
          this.marker = null;
        }

        this.codeNum = this.form.code;
        this.open = true;
        this.title = "修改门店";

        this.$nextTick(() => {
          if (!this.mapInstance) {
            this.initGaodeMap();
          }

          if (this.form.lng && this.form.lat) {
            const pos = new AMap.LngLat(this.form.lng, this.form.lat);
            this.mapInstance.setCenter(pos);
            this.marker = new AMap.Marker({ position: pos });
            this.mapInstance.add(this.marker);
          }
        });

      }).catch(error => {
        console.error("获取门店数据失败", error);
        this.$modal.msgError("获取门店数据失败");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.lng = this.selectedPosition.lng;
          this.form.lat = this.selectedPosition.lat;
          console.log(this.form.lng+","+this.form.lat)
          if (this.form.id != null) {
            updateShop(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            var orderCode = getOrderCode(this.ShopList);
            this.form.code = orderCode;
            addShop(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除门店编号为"' + ids + '"的数据项？').then(function() {
        return delShop(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/Shop/export', {
        ...this.queryParams
      }, `Shop_${new Date().getTime()}.xlsx`)
    },
  }
};

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="MD";
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(2,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      console.log(list);
      let listCode=list[i].code.slice(2,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
